/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import LZ4 from 'lz4js';
import fileio from '@ohos.fileio';

export async function lz4Compressed(src: string, dest: string): Promise<boolean> {
  try {
    let stat = fileio.statSync(src);
    let fd = fileio.openSync(src, 0o2);
    let buf = new ArrayBuffer(stat.size);
    fileio.readSync(fd, buf);
    let unitArray = new Uint8Array(buf)
    let compressed = LZ4.compress(unitArray)
    let arrayBuffer = new Uint8Array(compressed).buffer;
    //生成文件
    let newpath = fileio.openSync(dest, 0o102, 0o666)
    fileio.writeSync(newpath, compressed.buffer);

    return true;
  } catch (error) {
    return false;
  }
}

export async function lz4Decompressed(src: string, target: string): Promise<boolean> {
  try {
    let stat = fileio.statSync(src);
    let fd = fileio.openSync(src, 0o2);
    let buf = new ArrayBuffer(stat.size);
    fileio.readSync(fd, buf)
    let unitArray = new Uint8Array(buf)
    let decompress = LZ4.decompress(unitArray)
    let newpath = fileio.openSync(target, 0o102, 0o666)
    let num = fileio.writeSync(newpath, decompress.buffer);

    return true;
  } catch (error) {
    return false;
  }
}